package com.liu.juc.forkjoin;


import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinDemo1 extends RecursiveTask<Long> {

    private Long start;

    private Long end;

    // 临界值
    private Long temp = 10000L;

    public ForkJoinDemo1(Long start, Long end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Long compute() {

        Long sum = 0L;
        //平均个任务

        if ((end-start) < temp) {
            for (Long i = start; i < end; i++) {
                sum += i;
            }
        } else {
            Long middle = (end + start) / 2;
            // 递归
            ForkJoinDemo1 forkJoinDemo1 = new ForkJoinDemo1(start, middle);
            ForkJoinTask<Long> fork = forkJoinDemo1.fork();
            ForkJoinDemo1 forkJoinDemo2 = new ForkJoinDemo1(middle, end);
            ForkJoinTask<Long> fork1 = forkJoinDemo2.fork();
            sum = fork.join() + fork1.join();
        }

        return sum;
    }
}
